package com.example.common.util;

import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class MinioUtil {
    private static String minioUrl;
    private static String minioName;
    private static String minioPass;
    private static String bucketName;

    public static void setMinioUrl(String minioUrl) {
        MinioUtil.minioUrl = minioUrl;
    }

    public static void setMinioName(String minioName) {
        MinioUtil.minioName = minioName;
    }

    public static void setMinioPass(String minioPass) {
        MinioUtil.minioPass = minioPass;
    }

    public static void setBucketName(String bucketName) {
        MinioUtil.bucketName = bucketName;
    }

    public static String getMinioUrl() {
        return minioUrl;
    }

    public static String getBucketName() {
        return bucketName;
    }

    private static MinioClient minioClient = null;

    /**
     * 初始化客户端
     * 获取Minio客户端
     * @param minioUrl
     * @param minioName
     * @param minioPass
     * @return
     */
    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        if (minioClient == null) {
            try {
                //低版本Minioi MinioClient的获取方法，高版本Minio 不是这个获取方法
                minioClient = new MinioClient(minioUrl, minioName, minioPass);
            } catch (InvalidEndpointException e) {
                e.printStackTrace();
            } catch (InvalidPortException e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }

    /**
     * 异步上传文件，先返回文件路径
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static String syncUpload(MultipartFile file, String bizPath) {
        return syncUpload(file, bizPath, null);
    }

    /**
     * 异步上传文件，先返回文件路径
     *
     * @param file 上传的文件
     * @param customBucket 桶的名称
     * @param bizPath 在桶中的路径 例如 ecosystem/task/modulefile2
     * @return
     */
    public static String syncUpload(MultipartFile file, String bizPath, String customBucket) {
        String file_url = "";
        //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        bizPath = StrAttackFilter.filter(bizPath);
        //update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        String newBucket = bucketName;
        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        try {
            initMinio(minioUrl, minioName, minioPass);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(newBucket)) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(newBucket);
                System.out.println("create a new bucket.");
            }
            InputStream stream = file.getInputStream();
            // 获取文件名
            String orgName = file.getOriginalFilename();//获取上传文件的原名
            if ("".equals(orgName)) {
                orgName = file.getName();//获取表单中文件组件的名字
            }
            orgName = CommonUtils.getFileName(orgName);
            //这一步保证了文件名的唯一，因为加上了时间戳
            String objectName = bizPath + "/" + orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            ExecutorService fixedThreadPool = newFixedThreadPool(10);//得到一个线程池
            fixedThreadPool.execute(() -> {
                String newBucket1 = bucketName;
                if (oConvertUtils.isNotEmpty(customBucket)) {
                    newBucket1 = customBucket;
                }
                // 使用putObject上传一个本地文件到存储桶中。
                try {
                    minioClient.putObject(newBucket1, objectName, stream, stream.available(), "application/octet-stream");
                    stream.close();
                } catch (InvalidBucketNameException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (InsufficientDataException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (NoResponseException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (ErrorResponseException e) {
                    e.printStackTrace();
                } catch (InternalException e) {
                    e.printStackTrace();
                } catch (InvalidArgumentException e) {
                    e.printStackTrace();
                }
            });
            file_url = minioUrl + newBucket + "/" + objectName;
        } catch (IOException | InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | InvalidKeyException | NoResponseException | XmlPullParserException | ErrorResponseException | InternalException | RegionConflictException e) {
            System.out.println(e.getMessage());
        }
        return file_url;
    }

    /**
     * 普通上传文件 非异步
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static String upload(MultipartFile file, String bizPath) {
        return upload(file, bizPath, null);
    }


    /**
     * 普通上传文件 非异步
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file, String bizPath, String customBucket) {
        String file_url = "";
        //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        bizPath = StrAttackFilter.filter(bizPath);
        //update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        String newBucket = bucketName;
        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        try {
            initMinio(minioUrl, minioName, minioPass);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(newBucket)) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(newBucket);
                System.out.println("create a new bucket.");
            }
            InputStream stream = file.getInputStream();
            // 获取文件名
            String orgName = file.getOriginalFilename();
            if ("".equals(orgName)) {
                orgName = file.getName();
            }
            orgName = CommonUtils.getFileName(orgName);
            String objectName = bizPath + "/" + orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));

            // 使用putObject上传一个本地文件到存储桶中。
            minioClient.putObject(newBucket, objectName, stream, stream.available(), "application/octet-stream");
            stream.close();
            file_url = minioUrl + newBucket + "/" + objectName;
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (InvalidKeyException e) {
            System.out.println(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
        } catch (NoResponseException e) {
            System.out.println(e.getMessage());
        } catch (XmlPullParserException e) {
            System.out.println(e.getMessage());
        } catch (InvalidArgumentException e) {
            System.out.println(e.getMessage());
        } catch (RegionConflictException e) {
            System.out.println(e.getMessage());
        } catch (InvalidBucketNameException e) {
            System.out.println(e.getMessage());
        } catch (ErrorResponseException e) {
            System.out.println(e.getMessage());
        } catch (InternalException e) {
            System.out.println(e.getMessage());
        } catch (InsufficientDataException e) {
            System.out.println(e.getMessage());
        }
        return file_url;
    }

    /**
     * 获取某桶的某个的文件的文件流
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public static InputStream getMinioFile(String bucketName, String objectName) {
        InputStream inputStream = null;
        try {
            initMinio(minioUrl, minioName, minioPass);
            inputStream = minioClient.getObject(bucketName, objectName);
        } catch (Exception e) {
            System.out.println("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }

    /**
     * 判断文件是否存在
     *
     * @param url 传的参数是一个文件URL
     * @return
     * @throws XmlPullParserException
     * @throws InsufficientDataException
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws NoResponseException
     * @throws InvalidKeyException
     * @throws InternalException
     * @throws InvalidBucketNameException
     * @throws ErrorResponseException
     */
    public static Boolean checkFileExist(String url) {
        try {
            Boolean flag = false;
            initMinio(minioUrl, minioName, minioPass);
            String path = url.substring(url.indexOf(bucketName) + bucketName.length() + 1);
            Iterable<Result<Item>> myObjects = minioClient.listObjects(bucketName, path);
            try {
                for (Result<Item> result : myObjects) {
                    Item item = result.get();
                    System.out.println(item.objectName());
                    if (path.equals(item.objectName())) {
                        flag = true;
                    }
                }
            } catch (InvalidBucketNameException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InsufficientDataException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (NoResponseException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (ErrorResponseException e) {
                e.printStackTrace();
            } catch (InternalException e) {
                e.printStackTrace();
            }
            return flag;
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称
     */
    public static void deleteObjects(String bucketName, String objectName) {
        try {
            if (StringUtils.isNotBlank(objectName)) {
                initMinio(minioUrl, minioName, minioPass);
                Iterable<Result<Item>> list = minioClient.listObjects(bucketName, objectName);
                list.forEach(e -> {
                    try {
                        minioClient.removeObject(bucketName, e.get().objectName());
                    } catch (Exception ex) {
                        System.out.println("文件删除失败" + ex.getMessage());
                    }
                });
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件外链 获取文件外部链接
     *
     * @param bucketName
     * @param objectName
     * @param expires
     * @return
     */
    public static String getObjectURL(String bucketName, String objectName, Integer expires) {
        initMinio(minioUrl, minioName, minioPass);
        try {
            String url = minioClient.presignedGetObject(bucketName, objectName, expires);
            return URLDecoder.decode(url, "UTF-8");
        } catch (Exception e) {
            System.out.println("文件路径获取失败" + e.getMessage());
        }
        return null;
    }



}
